app.controller('CoryzaCtrl', function($rootScope, $ionicConfig, $http, $myconfig, $animateCss, $ionicPopup, $scope, $state, $stateParams, $timeout, $interval, BthSevice, SPAService, FetchDataService, radialIndicatorInstance) {

    //获取当前登录用户信息
    $scope.userMes = JSON.parse(localStorage.getItem('user'));

    //定义保养时间记时默认时间
    // SPAService.coryzaData.BGBsec = 0;

    //获取当前系统时间
    if (!$rootScope.start) { //如果是未保养那就用最新时间
        SPAService.coryzaData.ThisTime = new Date();
    }


    //定义定时器
    // var secTime;

    //定义保养模式默认名
    var mode;
    //定义设备名
    var deviceName = '金鼻光';

    // 定义默认保养状态
    // SPAService.coryzaData.maintain_sta = 0;


    var type = SPAService.coryzaData.type = $stateParams.type;
    console.log('type>>>>>>>>>>>>>>>>>>>>>>>>>>>.')
    console.log(type);
    $scope.valuesArr = [];
    $scope.typeTime = SPAService.coryzaData.typeTime = $rootScope.Bgb_time; //记录一份原始时间

    var biyan, jingxue, tongjingluo, tiaojique;

    var Count = 0;

    //开始保养
    function doIt() {
        switch (type) {
            case 'by': // 鼻腔
                // console.log(biyan);
                mode = '鼻腔';
                $rootScope.mode = '鼻腔';
                // $scope.valuesArr = useThis.biyan ? useThis.biyan : biyan;
                $scope.valuesArr = biyan;

                $scope.title = '鼻腔';
                $scope.typeSrc = 'img/icons/biyan.svg';
                // typeTime = $rootScope.Bgb_time;
                break;
            case 'jx': // 充能
                // console.log(jingxue);
                mode = '充能';
                $rootScope.mode = '充能';
                $scope.valuesArr = jingxue;

                $scope.title = '充能';
                $scope.typeSrc = 'img/icons/jingxue.svg';
                // typeTime = $rootScope.Bgb_time;
                break;
            case 'tjl': // 经络
                // console.log(tongjingluo);
                mode = '经络';
                $rootScope.mode = '经络';
                $scope.valuesArr = tongjingluo;

                $scope.title = '经络';
                $scope.typeSrc = 'img/icons/tongjingluo.svg';
                // typeTime = $rootScope.Bgb_time;
                break;
            default: // 自由模式
                // console.log(tiaojique);
                mode = '气血';
                $rootScope.mode = '气血';
                $scope.valuesArr = tiaojique;

                $scope.title = '气血';
                $scope.typeSrc = 'img/icons/tiaoqixue.svg';
        }
        SPAService.setCurrentData($scope.title, SPAService.coryzaData.BGBsec, $scope.userMes.id, deviceName, mode, SPAService.coryzaData.maintain_sta);

    };


    //日他，写的他妈的只能在此基础上改了 写的比较垃圾
    var ble_name = JSON.parse(localStorage.getItem(BthSevice.address)).name;
    var coryzaModeData = FetchDataService.getCoryzaModeData(); //金鼻光理疗数据
    $scope.deviceLED = function() {
        /*$http.get($myconfig.api.base_host + '/device/list_device_b')
            .then(function(res) {*/
                var minute = (parseInt(SPAService.coryzaData.typeTime/60).toString(16));
                if(minute.length == 1){
                    minute = '0' + minute;
                }
                // for (var i = 0; i < res.data.data.length; i++) {
                //     if (res.data.data[i].name == '金鼻光') {
                        for (var j = 0; j < coryzaModeData.mode.length; j++) {
                            if (j == 0) {
                                if (coryzaModeData.mode[j].colormode != 0) {
                                    if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                        biyan = [[
                                            '0x8a', //起始码
                                            '0x00',  //模式
                                            '0x00', //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), //红光
                                            '0xe6',  //绿光
                                            '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16))  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                        console.log('biyan:::::::::::::::::::');
                                        console.log(biyan);
                                    }else { //兼容以前
                                        biyan = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'], //开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x85', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式     ----静态
                                        ];
                                    }
                                } else {
                                    if (ble_name.indexOf('QMK-') > -1) { //搜索到的蓝牙名称必须包含QMK三个字母
                                        biyan = [[
                                            '0x8a', //起始码
                                            '0x18',  //模式
                                            '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x00', //红光
                                            '0x00',  //绿光
                                            '0x00'  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                        console.log('biyan:::::::::::::::::::');
                                        console.log(biyan);
                                    } else {
                                        biyan = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'],//开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x88', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式 --- 跳变
                                        ];
                                    }
                                }
                                localStorage.setItem('biyan', JSON.stringify(biyan));
                            } else if (j == 1) {
                                if (coryzaModeData.mode[j].colormode != 0) {
                                    if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                        jingxue = [[
                                            '0x8a', //起始码
                                            '0x00',  //模式
                                            '0x00', //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), //红光
                                            '0xe6',  //绿光
                                            '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16))  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                        console.log('jingxue:::::::::::::::::::');
                                        console.log(jingxue);
                                    }else {
                                        jingxue = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'], //开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x85', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式--- 静态;
                                        ];
                                    }
                                } else {
                                    if (ble_name.indexOf('QMK-') > -1) { //搜索到的蓝牙名称必须包含QMK三个字母
                                        jingxue = [[
                                            '0x8a', //起始码
                                            '0x18',  //模式 红蓝跳变
                                            '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x00', //红光
                                            '0x00',  //绿光
                                            '0x00'  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                        console.log('jingxue:::::::::::::::::::');
                                        console.log(jingxue);
                                    } else{
                                        jingxue = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'], //开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x88', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式 --- 跳变
                                        ];
                                    }
                                }
                                localStorage.setItem('jingxue', JSON.stringify(jingxue));
                            } else if (j == 2) { //---------------------------------------------------------------------------------------------------------
                                if (coryzaModeData.mode[j].colormode != 0) {
                                    if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                        tongjingluo = [[
                                            '0x8a', //起始码
                                            '0x00',  //模式
                                            '0x00', //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), //红光
                                            '0xe6',  //绿光
                                            '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16))  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                    }else {
                                        tongjingluo = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'], //开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x85', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式 --- 静态;
                                        ];
                                    }

                                } else {
                                    if (ble_name.indexOf('QMK-') > -1) { //搜索到的蓝牙名称必须包含QMK三个字母
                                        tongjingluo = [[
                                            '0x8a', //起始码
                                            '0x18',  //模式 红蓝跳变
                                            '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x00', //红光
                                            '0x00',  //绿光
                                            '0x00'  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                    } else {
                                        tongjingluo = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'], //开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x88', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式     ----跳变;
                                        ];
                                    }
                                }
                                localStorage.setItem('tongjingluo', JSON.stringify(tongjingluo));
                            } else if (j == 3) {
                                if (coryzaModeData.mode[j].colormode != 0) {
                                    if(ble_name.indexOf('QMK-') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                                        tiaojique = [[
                                            '0x8a', //起始码
                                            '0x00',  //模式
                                            '0x00', //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), //红光
                                            '0xe6',  //绿光
                                            '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16))  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                    }else {
                                        tiaojique = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'], //开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x85', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式--- 静态;
                                        ];
                                    }
                                } else {
                                    if (ble_name.indexOf('QMK-') > -1) { //搜索到的蓝牙名称必须包含QMK三个字母
                                        tiaojique = [[
                                            '0x8a', //起始码
                                            '0x18',  //模式 红蓝跳变
                                            '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), //速度
                                            '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), //亮度
                                            // '0x01', //倒计时
                                            '0x' + minute, //倒计时 分钟
                                            '0x00', //倒计时 秒
                                            '0x00', //红光
                                            '0x00',  //绿光
                                            '0x00'  //蓝光
                                            // '0xaf' //结束码
                                        ]];
                                    } else {
                                        tiaojique = [
                                            // ['0x7e', '0x04', '0x04', '0x01', '0xff', '0xff', '0xff', '0x00', '0xef'], //开关
                                            ['0x7e', '0x04', '0x01', '0x' + (parseInt(coryzaModeData.mode[j].redlight).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], //亮度
                                            ['0x7e', '0x04', '0x02', '0x' + (parseInt(coryzaModeData.mode[j].speed).toString(16)), '0xff', '0xff', '0xff', '0x00', '0xef'], // 设置速度
                                            ['0x7e', '0x07', '0x05', '0x' + (parseInt(coryzaModeData.mode[j].redscale).toString(16)), '0xe6', '0x' + (parseInt(coryzaModeData.mode[j].bluescale).toString(16)), '0x4d', '0x00', '0xef'], // 设置颜色强度
                                            ['0x7e', '0x05', '0x03', '0x88', '0x03', '0xff', '0xff', '0x00', '0xef'] // 设置模式   ----跳变;
                                        ];
                                    }
                                }
                                // console.log(tiaojique);
                                localStorage.setItem('tiaojique', JSON.stringify(tiaojique));
                            }
                        }
                    // }
                // }
                doIt();

            // });
    };
    $scope.deviceLED();

    $scope.indicatorOption = {
        radius: 80,
        percentage: false,
        displayNumber: false,
        barColor: "#18C756",
        barBgColor: "#D2F4DC",
        roundCorner: true,
        barWidth: 7,
        display: false,
        // frameTime: 1500,
        initValue: 0
    };

    var backcount = 0;
    /*if(SPAService.coryzaData.backcount){
        backcount = SPAService.coryzaData.backcount;
    }*/
    if (SPAService.coryzaData.backtime) {
        backcount = Math.ceil((new Date().getTime() - SPAService.coryzaData.backtime) / 1000); //已保养的时间差
    }
    console.log('backcount..............');
    console.log(backcount);
    if (!SPAService.coryzaData.ts) {
        $scope.ts = SPAService.coryzaData.ts = SPAService.coryzaData.typeTime; //80秒
        SPAService.coryzaData.BGBsec = 0; //计算保养时间
    } else {

        $scope.ts = SPAService.coryzaData.ts -= backcount; //倒计时
    }

    var every = 100 / SPAService.coryzaData.typeTime;
    if (!SPAService.coryzaData.rotateCount) {
        $scope.rotateCount = SPAService.coryzaData.rotateCount = 45; //默认圆点从45°位置，即钟表12点钟
    } else {
        $scope.rotateCount = SPAService.coryzaData.rotateCount += backcount * 6; //加上离开的时间的角度
    }
    if (!SPAService.coryzaData.progress) {
        SPAService.coryzaData.progress = 0;
    } else {
        SPAService.coryzaData.progress += (every * backcount);
        // radialIndicatorInstance['indicator2'].animate(SPAService.coryzaData.progress); //恢复现在的进度
        Count = $interval(down, 1000);

    }


    // SPAService.coryzaData.progress = 0; // 进度

    function down() {
        if (SPAService.coryzaData.ts < 0) {
            $interval.cancel(Count);
            $scope.resetTime(); // 重置
            BthSevice.closeLED(); // 完成后关闭led
            $rootScope.start = false; //停止运行
            SPAService.coryzaData.maintain_sta = 1;
            SPAService.setCurrentData($scope.title, SPAService.coryzaData.BGBsec, $scope.userMes.id, deviceName, mode, SPAService.coryzaData.maintain_sta);
            SPAService.backgroundRunning(true, new Date(), function() { //去记录当前的保养数据
                $rootScope.start = false; //停止运行
                $state.go('app.CoryzaEnd', {
                    type: $scope.title
                });
            });
            /*$http.post($myconfig.api.base_host + '/users/maintain', {
                "user_id": $scope.userMes.id,
                "dev_name": deviceName,
                "mode": mode,
                "duration": SPAService.coryzaData.BGBsec,
                "state": SPAService.coryzaData.maintain_sta,
                "createtime": SPAService.coryzaData.ThisTime
            }).then(function(res) {
                // console.log(res.data.data);
                // $interval.cancel(secTime);
                SPAService.coryzaData.BGBsec = 0;
                // Math
                $http.get($myconfig.api.base_host + '/physicallogs/finsh?user_id=' + $scope.userMes.id + '&mode=' + mode + '&dev_name=' + deviceName)
                    .then(function(res) {
                        // console.log(res.data.data);
                        res.data.data.duration = ((res.data.data.duration) / 60).toFixed(1);
                        res.data.data.totle_duration = ((res.data.data.totle_duration) / 60).toFixed(1);
                        $rootScope.finsh = res.data.data;
                        $http.get($myconfig.api.base_host + '/users/user_info?mobile=' + $rootScope._RootUser.mobile)
                            .then(function(res) {
                                if (res.data.success) {
                                    localStorage.setItem('user', JSON.stringify(res.data.data));
                                }
                            });
                    });
            });*/
            // $state.go('app.CoryzaEnd', {
            //     type: $scope.title
            // });
            return;
        }
        SPAService.coryzaData.rotateCount += 6;
        /*console.log('~~~~~~~~~~~~~~~~~~');
        console.log(SPAService.coryzaData.rotateCount);
        console.log($scope.rotateCount);*/
        $scope.rotateCount = SPAService.coryzaData.rotateCount;
        // if($scope.rotateCount == 405){ //转了一圈了
        //     $scope.rotateCount = SPAService.coryzaData.rotateCount = 45;
        // }
        $scope.ngrotate = {
            '-webkit-transform': 'rotate(' + SPAService.coryzaData.rotateCount + 'deg)'
        }

        SPAService.coryzaData.BGBsec++;
        SPAService.coryzaData.progress += every; //每次执行进度条动多少
        radialIndicatorInstance['indicator2'].animate(SPAService.coryzaData.progress);
        $scope.ts = SPAService.coryzaData.ts = SPAService.coryzaData.ts - 1;
    }

    $scope.resetTime = function() {
        $scope.ts = SPAService.coryzaData.ts = SPAService.coryzaData.typeTime;
        SPAService.coryzaData.progress = 0;
        radialIndicatorInstance['indicator2'].animate(0); //重置为原点
        $("#zhuan2").removeClass('tf');
        if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
        }
    };
    var myPopup;

    // $("#zhuan2").css("animation-play-state", "paused");
    $scope.cancelTimer = function() {
        $scope.msg = '您确定要结束本次保养吗？';
        myPopup = $ionicPopup.show({
            templateUrl: 'templates/bitongbao/module/tishi.html',
            scope: $scope
        });
        $scope.myclose = function() {
            myPopup.close();
        };
        $scope.ok = function() {
            localStorage.removeItem('lastSPAEnd');
            myPopup.close();
            $rootScope.start = false; //停止运行
            $interval.cancel(Count);
            Count = null;
            $scope.resetTime();
            $scope.state = '开始';
            BthSevice.closeLED(); // 完成后关闭led
            $scope.changePage = true;
            SPAService.coryzaData.maintain_sta = '0';
            $http.post($myconfig.api.base_host + '/users/maintain', {
                "user_id": $scope.userMes.id,
                "dev_name": deviceName,
                "mode": mode,
                "duration": SPAService.coryzaData.BGBsec,
                "state": SPAService.coryzaData.maintain_sta,
                "createtime": SPAService.coryzaData.ThisTime
            }).then(function(res) {
                // console.log(res.data.data);
                // $interval.cancel(secTime);
                SPAService.coryzaData.BGBsec = 0;
                $rootScope.start = false;
                SPAService.coryzaData = { stateText: '开始' };
                $http.get($myconfig.api.base_host + '/users/user_info?mobile=' + $rootScope._RootUser.mobile)
                    .then(function(res) {
                        if (res.data.success) {
                            localStorage.setItem('user', JSON.stringify(res.data.data));
                        }
                    });
            });

            if (device.platform == "Android") {
              cordova.plugins.notification.local.cancel(1000, function () {
                  console.log('本地通知已取消');
              });
            }else { //ios直接清楚本地通知的所有对象，清除所有，应该没有其他的了吧
              window.plugins.jPushPlugin.clearAllLocalNotifications();
            }

            $state.go('app.BiGuangBao');
        };

    };

    if (SPAService.coryzaData.stateText) {
        $scope.state = SPAService.coryzaData.stateText;
    } else {
        $scope.state = SPAService.coryzaData.stateText = '开始';
    }

    $scope.started = function() {
        if ($scope.state == '开始') {
            $rootScope.start = true; //启动状态
            $scope.state = SPAService.coryzaData.stateText = '暂停';
            localStorage.setItem('lastSPAEnd', JSON.stringify({
                status: false,
                user_id: $scope.userMes.id,
                dev_name: deviceName,
                mode: mode,
                duration: SPAService.coryzaData.BGBsec,
                state: SPAService.coryzaData.maintain_sta,
                createtime: SPAService.coryzaData.ThisTime,
                type: 'nose',
                typeTime: $scope.typeTime,
                spa_type: SPAService.coryzaData.type,
                stateText: SPAService.coryzaData.stateText
            }));

            // SPAService.coryzaData.radialIndicatorInstance = radialIndicatorInstance['indicator2'];

            BthSevice.write($scope.valuesArr); // 开始之后亮起设置led
            console.log($scope.valuesArr);
            // console.log(valuesArr);
            $interval.cancel(Count);
            $scope.resetTime();
            // $("#zhuan2").addClass('tf');
            Count = $interval(down, 1000);

            setSchedule(SPAService.coryzaData.typeTime * 1000); //开启本地通知,规定的时间完成后本地通知完成

            // $("#zhuan2").css("animation-play-state", "running");
        } else if ($scope.state == '暂停') {
            localStorage.setItem('lastSPAEnd', JSON.stringify({status: true}));

            BthSevice.closeLED(); // 完成后关闭led
            $rootScope.start = false; //暂停状态
            $scope.state = SPAService.coryzaData.stateText = '继续';
            $interval.cancel(Count);

            // cordova.plugins.notification.local.cancel(1000, function () { //先取消，等继续后再创建定时器
            //     console.log('本地通知已取消');
            // });
            if (device.platform == "Android") {
              cordova.plugins.notification.local.cancel(1000, function () {
                  console.log('本地通知已取消');
              });
            }else {
              window.plugins.jPushPlugin.clearAllLocalNotifications();
            }
            // $("#zhuan2").addClass('tf');
            // Count = $interval(down, 1000);
            // $("#zhuan2").css("animation-play-state", "paused");
        } else { //继续
            $rootScope.start = true; //启动状态
            $scope.state = SPAService.coryzaData.stateText = '暂停';

            localStorage.setItem('lastSPAEnd', JSON.stringify({
                status: false,
                user_id: $scope.userMes.id,
                dev_name: deviceName,
                mode: mode,
                duration: SPAService.coryzaData.BGBsec,
                state: SPAService.coryzaData.maintain_sta,
                createtime: SPAService.coryzaData.ThisTime,
                type: 'nose',
                typeTime: $scope.typeTime,
                spa_type: SPAService.coryzaData.type,
                stateText: SPAService.coryzaData.stateText
            }));


            var time = SPAService.coryzaData.ts; //如果继续计算剩余的时间
            console.log('剩余时间：' + time);
            var minutes = Math.floor(time/60); //剩余时间
            minutes = (parseInt(minutes).toString(16));
            if(minutes.length == 1){
                minutes = '0' + minutes;
            }

            var seconds = (time-Math.floor(time/60)*60); //剩余秒钟
            seconds = (parseInt(seconds).toString(16));
            if(seconds.length == 1){
                seconds = '0' + seconds;
            }
            $scope.valuesArr[0].splice(
                4,
                2,
                '0x' + minutes,
                '0x' + seconds)

            BthSevice.write($scope.valuesArr); // 开始之后亮起设置led
            console.log($scope.valuesArr);
            Count = $interval(down, 1000);

            setSchedule(time); //开启本地通知
            // $("#zhuan2").css("animation-play-state", "running");
        }
    };

    function setSchedule(time) {
      if(device.platform == 'Android'){ //安卓的走这个插件的本地通知
        cordova.plugins.notification.local.schedule({
            id: 1000,
            title: '健康保养',
            text: '您正在进行的' + $rootScope.mode + '保养已完成。',
            at: new Date().getTime() + time,
            // badge: 1,
            autoClear: true, //默认值
            // sound: 'res://platform_default', //默认值
            // sound: 'file://sound.mp3', //播放声音
            icon: 'res://drawable-xxxhdpi/icon.png', //默认值
            ongoing: false //默认值
        });
      }else {
        window.plugins.jPushPlugin.addLocalNotificationForIOS(
          time / 1000,
          '您正在进行的' + $rootScope.mode + '保养已完成。',
          1,
          "1000", {"key":"value"}
        );
      }
    }

    $scope.$on('$destroy', function() {
        $interval.cancel(Count);
    });

    SPAService.coryzaData.thePage = true; //标记在保养页面 在保养界面就不需要定时器发送保养数据到服务器
    $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options) {
        console.log(SPAService.coryzaData);
        SPAService.coryzaData.thePage = false; //标记为离开
        if (toState.name == 'app.BiGuangBao' && !$scope.changePage) {

            if (!$rootScope.start) { //停止状态直接清除数据
                $interval.cancel(Count);
                Count = null;
                $scope.resetTime();
                // $("#zhuan2").css("animation-play-state", "paused");
                BthSevice.closeLED(); // 完成后关闭led
                $scope.changePage = true;
                SPAService.coryzaData = { stateText: '开始' };
                // $state.go('app.BiGuangBao');
            } else {
                SPAService.coryzaData.backtime = new Date().getTime(); //记录返回到首页的时间
                SPAService.coryzaData.maintain_sta = 1; //从这里返回默认为可以保养完成

                /*cordova.plugins.notification.local.schedule({
                    id: 1000,
                    title: '健康保养',
                    text: '您正在进行的' + $rootScope.mode + '保养已完成。',
                    at: new Date().getTime() + 5000,
                    // badge: 1,
                    autoClear: true, //默认值
                    sound: 'res://platform_default', //默认值
                    icon: 'res://drawable-xxxhdpi/icon.png', //默认值
                    ongoing: false //默认值
                });*/
            }


            return; //后面的先不执行
            event.preventDefault();
            $scope.msg = '您确定要结束本次保养吗？';
            myPopup = $ionicPopup.show({
                templateUrl: 'templates/bitongbao/module/tishi.html',
                scope: $scope
            });
            $scope.myclose = function() {
                myPopup.close();
            };
            $scope.ok = function() {
                myPopup.close();
                $rootScope.start = false;
                maintain_sta = '0';
                if (SPAService.coryzaData.BGBsec / 60 >= 6) {
                    $http.post($myconfig.api.base_host + '/users/maintain', {
                        "user_id": $scope.userMes.id,
                        "dev_name": deviceName,
                        "mode": mode,
                        "duration": SPAService.coryzaData.BGBsec,
                        "state": maintain_sta,
                        "createtime": SPAService.coryzaData.ThisTime
                    }).then(function(res) {
                        SPAService.coryzaData.BGBsec = 0;
                        $http.get($myconfig.api.base_host + '/users/user_info?mobile=' + $rootScope._RootUser.mobile)
                            .then(function(res) {
                                if (res.data.success) {
                                    localStorage.setItem('user', JSON.stringify(res.data.data))
                                }
                            });
                    });
                }
                $interval.cancel(Count);
                $scope.resetTime();
                $("#zhuan2").css("animation-play-state", "paused");
                BthSevice.closeLED(); // 完成后关闭led
                $scope.changePage = true;
                $state.go('app.BiGuangBao');
            };
        } else if (myPopup) {
            myPopup.close();
        }
    });

    $scope.$on('$destroy',function(){
        $interval.cancel(Count);
    });

    $scope.goBack = function() {
        $state.go('app.BiGuangBao');
    };
    $scope.$on('$ionicView.enter', function() {

        $ionicConfig.views.swipeBackEnabled(false);

    });

    //退出的时候取消当前页定时器
    $scope.$on('stopInterval', function (event) {
        // $interval.cancel(Count);
    });

    //程序从后台恢复时会收到此事件通知
    $scope.$on('isResume', function (event, data) {
        if(data){
            // $interval.cancel(Count);
            console.log('校准倒计时效果');
            if (SPAService.coryzaData.backtime) {
                backcount = Math.ceil((new Date().getTime() - SPAService.coryzaData.backtime) / 1000)
                console.log('程序在后台运行' + backcount + '秒 ' + SPAService.coryzaData.backtime);
                console.log('程序在后台运行' + backcount/60 + '分钟 ');

            }

            $scope.ts = SPAService.coryzaData.ts = SPAService.coryzaData.backts -= backcount; //倒计时

            var every = 100 / SPAService.coryzaData.typeTime;

            $scope.rotateCount = SPAService.coryzaData.rotateCount = SPAService.coryzaData.backrotateCount += backcount * 6; //加上离开的时间的角度

            SPAService.coryzaData.progress = SPAService.coryzaData.backprogress += (every * backcount);

        }
    });

});
